import { useEffect, useMemo, useState } from 'react'
import { useLocation } from 'react-router-dom'
import { NavBar, Card, Skeleton, Toast } from 'antd-mobile'
import { LeftOutline } from 'antd-mobile-icons'
import request from '../../api/request'
import './index.css'

interface InformationDetail {
  id: number
  title: string
  content: string
  source: string
  releaseTime: number
  whetherCollection?: number
}

export default function InformationDetailPage() {
  const location = useLocation()
  const [detail, setDetail] = useState<InformationDetail | null>(null)
  const [loading, setLoading] = useState(true)

  const infoId = useMemo(() => {
    const sp = new URLSearchParams(location.search)
    const id = sp.get('id')
    return id ? Number(id) : undefined
  }, [location.search])

  const formatTime = (ts: number) => {
    const d = new Date(ts)
    const y = d.getFullYear()
    const m = `${d.getMonth() + 1}`.padStart(2, '0')
    const day = `${d.getDate()}`.padStart(2, '0')
    const hh = `${d.getHours()}`.padStart(2, '0')
    const mm = `${d.getMinutes()}`.padStart(2, '0')
    return `${y}-${m}-${day} ${hh}:${mm}`
  }

  const fetchDetail = async (id: number) => {
    setLoading(true)
    try {
      const res = await request.get('/health/share/information/v1/findInformation', {
        params: { infoId: id }
      })
      if (res.status === 200 && res.data?.result) {
        setDetail(res.data.result)
      } else {
        Toast.show({ content: res.data?.message || '获取详情失败' })
      }
    // eslint-disable-next-line @typescript-eslint/no-unused-vars
    } catch (error) {
      Toast.show({ content: '网络错误，请稍后重试' })
    } finally {
      setLoading(false)
    }
  }

  useEffect(() => {
    if (infoId) fetchDetail(infoId)
  }, [infoId])

  return (
    <div className='info-detail-page'>
      <NavBar className="sticky-navbar" backArrow={<LeftOutline />} onBack={() => history.back()}>资讯详情</NavBar>

      <Card className='info-card'>
        {loading ? (
          <Skeleton animated style={{ padding: 12 }} />
        ) : detail ? (
          <div className='info-container'>
            <h1 className='info-title'>{detail.title}</h1>
            <div className='info-meta'>
              <span className='info-source'>{detail.source || '佚名'}</span>
              <span className='info-time'>{formatTime(detail.releaseTime)}</span>
            </div>
            <div
              className='info-content'
              dangerouslySetInnerHTML={{ __html: detail.content || '' }}
            />
          </div>
        ) : (
          <div className='info-empty'>暂无数据</div>
        )}
      </Card>
    </div>
  )
}
